<template>
  <el-form
    class="overview-edit"
    :rules="formRule"
    ref="elFormCom"
    :model="formModel"
    :hide-required-asterisk="preview"
  >
    <el-form-item label="企业名称" prop="enterpriseName" label-position="top" maxlength="30">
      <el-input
        v-model="formModel.enterpriseName"
        placeholder="请输入企业名称"
        :readonly="preview"
      />
    </el-form-item>
    <el-form-item label="企业地址" label-position="top" prop="enterpriseAddress">
      <el-form-item>
        <el-cascader :options="regionData" v-model="addressPrefix" placeholder="请选择 省/市/区">
        </el-cascader>
      </el-form-item>
      <el-form-item style="margin-left: 10px">
        <el-input v-model="addressDetail" placeholder="请输入街道/小区/乡镇/村等" />
      </el-form-item>
    </el-form-item>
    <el-form-item label="企业Logo" label-position="top" prop="enterpriseLogo">
      <upload-image :limit="1" v-model="formModel.enterpriseLogo" :readonly="preview" />
    </el-form-item>
    <el-form-item label="营业执照" label-position="top" prop="enterpriseCharter">
      <upload-image :limit="1" v-model="formModel.enterpriseCharter" :readonly="preview" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import _ from 'lodash'
import { regionData } from 'element-china-area-data'
import { computed, readonly, ref, watch } from 'vue'
import UploadImage from '@/components/ImageUpload'
const elFormCom = ref()
const props = defineProps({
  model: {
    type: Object,
    default: () => ({
      enterpriseName: '',
      enterpriseAddress: '',
      enterpriseLogo: '',
      enterpriseCharter: '',
    }),
  },
  preview: {
    type: Boolean,
    default: false,
  },
})
const formModel = reactive(_.cloneDeep(props.model))
const formRule = {
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { max: 30, message: '企业名称长度在 1 到 30 个字符', trigger: 'blur' },
  ],
  enterpriseAddress: [{ required: true, message: '请补充企业地址', trigger: 'blur' }],
  enterpriseCharter: [{ required: true, message: '请上传企业营业执照', trigger: 'blur' }],
}

const addressPrefix = computed({
  get() {
    const arr = formModel.enterpriseAddress.split('/')
    arr.pop()
    return arr
  },
  set(val) {
    formModel.enterpriseAddress = val.join('/') + '/' + addressDetail.value
  },
})
const addressDetail = computed({
  get() {
    const arr = formModel.enterpriseAddress.split('/')
    return arr.pop()
  },
  set(val) {
    formModel.enterpriseAddress = addressPrefix.value.join('/') + '/' + val
    console.log(formModel)
  },
})

const submit = () => {
  return new Promise((resolve, reject) => {
    elFormCom.value.validate((valid) => {
      if (valid) {
        resolve(formModel)
      } else {
        reject()
      }
    })
  })
}

defineExpose({ submit })
</script>

<style lang="scss">
.overview-edit {
  .el-input {
    width: 400px;
  }
}
</style>
